<template>
  <div>
    <!--面包屑导航区域-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!--卡片视图-->
    <el-card>
      <!--添加角色按钮-->
      <el-row>
        <el-col>
          <el-button type="primary" @click="showAddRoleDialog">添加角色</el-button>
        </el-col>
      </el-row>
    </el-card>
    <el-table :data="rolesList" border stripe>
      <el-table-column type="expand">
        <template v-slot="scope">
          <el-row :class="['bdBottom',index1==0?'bdTop':'','vcenter']" v-for="(item1,index1) in scope.row.children" :key="item1.id">
            <!--渲染一级权限-->
            <el-col :span="5">
              <el-tag closable @close="removeRightsById(scope.row,item1.psId,scope.row.psIds)">{{item1.psName}}</el-tag>
              <i class="el-icon-caret-right"></i>
            </el-col>
            <!--渲染2级和3级权限-->
            <el-col :span="19">
              <!--for循序 嵌套渲染2级权限-->
              <el-row :class="[index2!=0?'bdTop':'','vcenter']" v-for="(item2,index2) in item1.children" :key="item2.id">
                <el-col :span="6">
                  <el-tag type="success" closable @close="removeRightsById(scope.row,item2.psId,scope.row.psIds)">{{item2.psName}}</el-tag>
                </el-col>
                <!--渲染三级权限-->
                <el-col :span="18">
                  <el-tag @close="removeRightsById(scope.row,item3.psId,scope.row.psIds)" closable type="warning" v-for="(item3,index3) in item2.children" :key="item3.id">
                    {{item3.psName}}
                  </el-tag>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
          <!--<pre>{{scope.row}}}</pre>-->
        </template>
      </el-table-column>
      <el-table-column type="index" label="ID"></el-table-column>
      <el-table-column prop="roleName" label="角色名称"></el-table-column>
      <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
      <el-table-column prop="roleDesc" label="操作">
        <template v-slot="scope">
          <el-tooltip content="编辑权限" placement="top" effect="dark" :enterable="false">
            <el-button type="primary" size="mini" icon="el-icon-edit" @click="showEditDialog(scope.row)">编辑</el-button>
          </el-tooltip>
          <el-tooltip content="删除权限" placement="top" effect="dark" :enterable="false">
            <el-button type="danger" size="mini" icon="el-icon-delete" @click="deleteRole(scope.row.roleId)">删除</el-button>
          </el-tooltip>
          <el-tooltip content="分配权限" placement="top" effect="dark" :enterable="false">
            <el-button type="warning" size="mini" icon="el-icon-star-off" @click="showRightsDialog(scope.row)">分配权限</el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <!--分配权限对话框-->
    <el-dialog
      title="分配权限"
      :visible.sync="rightsDialogVisible"
      width="30%" @close="setRightDialogResete">
      <!--树形组件-->
      <el-tree :data="rightsList" :props="treeProps"
               show-checkbox node-key="psId"
               default-expand-all
               :default-checked-keys="defKeys" ref="treeRef"></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="rightsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
    <!--编辑权限对话框-->
    <el-dialog
      title="编辑权限"
      :visible.sync="editDialogVisible"
      width="30%" @close="editCloseDialog">
      <el-form ref="editFormRef" :model="editForm" label-width="80px" :rules="editFormRules">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="editDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="editFormInfo">确 定</el-button>
  </span>
    </el-dialog>

    <!--添加角色对话框-->
    <el-dialog
      title="添加角色"
      :visible.sync="addDialogVisible"
      width="30%" @close="addCloseDialog">
      <el-form ref="addFormRef" :model="addForm" label-width="80px" :rules="addFormRules">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="addDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="addFormInfo">确 定</el-button>
  </span>
    </el-dialog>
  </div>
</template>

<script>
    export default {
      name: "Roles",
      data(){
          return{
            rolesList:[],
            //控制分配权限对话框显示和隐藏
            rightsDialogVisible:false,
            //分配权限弹框树形数据显示
            rightsList:[],
            //树形控件绑定属性
            treeProps:{
              children: 'children',
              label: 'psName'
            },
            //树形控件默认选中状态
            defKeys:[],
            //保存当前分配角色id
            roleId:'',
            rightsId:'',
            //编辑对话框显示和隐藏属性
            editDialogVisible:false,
            editForm:{},
            editFormRules:{
              roleName:[{required:true,message: '请输入角色名称',trigger:'blur'}],
              roleDesc:[{required:true,message: '请输入角色描述',trigger:'blur'}]
            },
            editRoleId:'',
            //添加角色对话框显示和隐藏
            addDialogVisible : false,
            addForm:{
              roleName:'',
              roleDesc:''
            },
            addFormRules:{
              roleName:[{required:true,message: '请输入角色名称',trigger:'blur'}],
              roleDesc:[{required:true,message: '请输入角色描述',trigger:'blur'}]
            }
          }
      },
      created() {
        this.getRolesList();
      },
      methods:{
        async getRolesList(){
          const {data:res} = await this.$axios.get('roles');
          if(res.code != 200) {
            return this.$message.error("获取角色失败")
          }
          this.rolesList = res.data;
          //console.log(this.rolesList);
        },
        //根据id删除对应的权限
        async removeRightsById(role,psId,psIds){
          const confirmResult = await this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).catch(err=>err);
          if(confirmResult != 'confirm') {
            return this.$message.info("已取消操作");
          }
          const {data:res} = await this.$axios.get('/delete/'+role.roleId+'/'+psId,{params:{psIds:psIds}});
          //console.log(res);
          if(res.code != 200) {
            return this.$message.success("删除权限失败,请确认")
          }
          //this.getRolesList();
          role.children = res.data;
          this.$message.success("删除权限成功")
        },
        //显示分配权限对话框
        async showRightsDialog(role){
          this.roleId = role.roleId;
          //console.log(this.roleId);
          this.rightsId = role.psIds;
          //console.log(this.rightsId);
          //获取权限列表
          const {data:res} = await this.$axios.get("rightsList");
          if (res.code !=200) {
            return this.$message.error("获取权限列表失败")
          }
          this.rightsList = res.data;
          //console.log(this.rightsList);
          //采用递归方式
          this.getLevelDefKeys(role,this.defKeys);
          this.rightsDialogVisible = true;
        },
        //采用递归方式，获取角色下面所有 三级权限id 并保存defkefs数组中
        getLevelDefKeys(node,arr){
          //如果当前节点不包含children 属性说明是三级节点
          if(!node.children) {
            return arr.push(node.psId);
          }
          //采用递归把 3级权限 push defKeys 数组中
          node.children.forEach(item=>{
            this.getLevelDefKeys(item,arr);
          })
        },
        //监听对话框关闭后重置 defKeys 数组
        setRightDialogResete(){
          this.defKeys = [];
          this.roleId = '';
          this.rightsId = ''
        },
        //点击为角色分配权限
        async allotRights(){
          const keys = [
            this.$refs.treeRef.getCheckedKeys(),
            this.$refs.treeRef.getHalfCheckedKeys()
          ];
          //const ids = keys.join(".");
          //console.log(ids)
          const {data:res} = await this.$axios.post("update/"+this.roleId,'ids='+keys+'&psIds='+this.rightsId);
          if(res.code !=200) {
            return this.$message.error("分配权限失败")
          }
          this.$message.success("分配权限成功")
          this.getRolesList();
          this.rightsDialogVisible = false;
        },
        //根据角色id 删除角色信息
        async deleteRole(roleId) {
           const confirmResult = await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
           }).catch(err=>err);
           if (confirmResult != 'confirm') {
             return this.$message.info("已取消操作");
           }
           const {data:res} = await this.$axios.get("delete/"+roleId);
           if(res.code != 200) {
             return this.$message.error("删除角色失败")
           }
          this.$message.success("删除角色成功");
          this.getRolesList();
        },
        //显示对话框方法
        showEditDialog(row){
          this.editForm = row;
          //console.log(this.editForm);
          this.editRoleId = row.roleId;
          this.editDialogVisible = true;
        },
        //关闭对话框重置表单校验
        editCloseDialog() {
          this.editRoleId = '';
          this.editForm = {};
          this.$nextTick(()=>{
            this.$refs.editFormRef.resetFields();
          })
        },
        //编辑角色提交方法
        editFormInfo(){
          this.$refs.editFormRef.validate(async valid=>{
              if(!valid) return;
              const {data:res} = await this.$axios.put("update/info/"+this.editRoleId,
                'roleName='+this.editForm.roleName+'&roleDesc='+this.editForm.roleDesc);
              console.log(this.editForm);
              if(res.code != 200) {
                return this.$message.error("编辑角色失败");
              }
              this.$message.success("编辑角色成功")
              this.getRolesList();
              this.editDialogVisible = false;
          })
        },
        //添加角色对话框显示方法
        showAddRoleDialog(){
          this.addDialogVisible = true;
        },
        //关闭添加角色对话框重置表单验证
        addCloseDialog(){
          this.$refs.addFormRef.resetFields();
        },
        //添加角色
        addFormInfo() {
          this.$refs.addFormRef.validate(async valid=>{
              if(!valid) return;
              const {data:res} = await this.$axios.post("add/role",this.addForm);
              if(res.code != 200) {
                 return this.$message.error("添加角色失败");
              }
              this.$message.success("添加角色成功");
              this.getRolesList();
              this.addDialogVisible = false;
          })

        }
      }
    }
</script>

<style scoped>
  .el-tag{
    margin: 7px;
  }
  .bdTop{
    border-top: 1px solid #eee;
  }
  .bdBottom{
    border-bottom: 1px solid #eee;
  }
  .vcenter{
    display: flex;
    align-items: center;
  }
</style>
